﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace EncryptionConsole
{
    class Program
    {
        private static CngKey _aliceKeySignature;
        private static byte[] _alicePubKeyBlob;
        static void Main(string[] args)
        {
            InitKeys();
            byte[] aliceData = Encoding.UTF8.GetBytes("Alice");
            byte[] aliceSignature = CreateSign(aliceData, _aliceKeySignature);
            Console.WriteLine($"Alice sign:{ Convert.ToBase64String(aliceSignature)}");
            if (VerifySign(aliceData, aliceSignature, _alicePubKeyBlob))
            {
                Console.WriteLine("Verifyed Successfully");
            }

            Console.ReadLine();
        }

        private static void InitKeys()
        {
            _aliceKeySignature = CngKey.Create(CngAlgorithm.ECDsaP521);
            _alicePubKeyBlob=_aliceKeySignature.Export(CngKeyBlobFormat.GenericPublicBlob);
        }

        private static byte[] CreateSign(byte[] data, CngKey key)
        {
            byte[] sign;
            using (var signingAlg = new ECDsaCng(key))
            {
             #if NET46
               sign=signingAlg.SignData(data);
                sign.Clear();
             #else
                sign = signingAlg.SignData(data, HashAlgorithmName.SHA512);
             #endif
            }
            return sign;
        }

        private static bool VerifySign(byte[] data, byte[] sign, byte[] pubKey)
        {
            bool retValue = false;
            using (CngKey key = CngKey.Import(pubKey, CngKeyBlobFormat.GenericPublicBlob))
            using (var signingAlg = new ECDsaCng(key))
            {
#if NET46
retValue=signingAlg.VerifyData(data,sign);
                signingAlg.Clear();
#else
                retValue = signingAlg.VerifyData(data, sign, HashAlgorithmName.SHA512);
#endif
            }
            return retValue;
        }
    }
}
